# coding: utf-8
import re
import datetime
import time
import json
import redis
from twisted.internet import reactor, task, protocol
from twisted.internet import defer, threads
from twisted.internet.protocol import Protocol, error, Factory
from twisted.protocols.basic import LineReceiver
r = redis.Redis(host='127.0.0.1',port=6379,db=0)
def getCurrentStrTime():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
class GasServerProtocol(LineReceiver):
    def __init__(self, factory):
        self.id = ''
        self.factory = factory
    def connectionMade(self):
        print((
            "[%s]:  %s连接到服务器端。" %
            (getCurrentStrTime(), self.transport.getPeer())))
        self.sendLine("$99'".encode('utf-8'))
    def connectionLost(self, reason):
        if self.id in self.factory.clients:
            del self.factory.clients[self.id]
            print("[%s]:ID %s 下线" % (getCurrentStrTime(), self.id))
        print((
            "[%s]:  %s断开了连接,原因是%s" %
            (getCurrentStrTime(),
             self.transport.getPeer(),
             reason)))
    def lineReceived(self, data):
        data = data.decode('utf-8')
        tmpstr = ("[%s]: 收到数据 %s") % (getCurrentStrTime(), data)
        print(tmpstr)
        if(re.match("\$\d{2}\$", data)):
            self.id = str(data[1:3])
            dicttmp = {}
            dicttmp['handle'] = self
            dicttmp['timestamp'] = time.time()
            self.factory.clients[self.id] = dicttmp
            print("[%s]:ID %s 注册成功" % (getCurrentStrTime(), self.id))
        if(re.match('@\d{2}\D\w{4}\d{2}',data)):
            if(data[3] == 'D'):
                print('接收到1条命令！\r\n')
                volttmp = (int(data[4:8],16)/1000.0)
                tmpstr = "当前电压值=%.3f" % volttmp
                print(tmpstr)
                dicttmp = {}
                dicttmp['collecttime'] = getCurrentStrTime()
                dicttmp['volt'] = volttmp
                dicttmp['id'] = self.id
                r.set(self.id, json.dumps(dicttmp))
                print(r.get(self.id))
class GasServerFactory(Factory):
    def __init__(self):
        self.clients = {}  # maps clients ids to GasServerProtocol instances
        self._lc = task.LoopingCall(self.send_to_clients)
        self._lc.start(3,now=False)
    def buildProtocol(self, addr):
        return GasServerProtocol(self)
    def send_to_clients(self):
        for client_addr in self.clients :
            self.clients[client_addr]['handle'].sendLine('hello!'.encode('utf-8'))
def startMoniter():
    print("[%s]启动监控服务" % getCurrentStrTime())
    cf = GasServerFactory()
    reactor.listenTCP(8234, cf)
    reactor.run()
def stopMoniter():
    print("[%s]停止监控服务" % getCurrentStrTime())
    try:
        reactor.crash()
    except RuntimeError:
        return defer.fail()
    else:
        return defer.succeed(None)
startMoniter()
